﻿require("../framework/vendor/validate");

_ = require("lodash/core");
_.assign = require("lodash/assign");
_.cloneDeep = require("lodash/cloneDeep");
_.get = require("lodash/get");

require('input-validate.directive');

require('./js/aui');

window.AUI = require("../framework/js/aui/index");

require("../framework/js/aui/components/loading.component");

require('aui.form-file');

require('aui.pagination');

require('aui.codeshow');

require('aui.modal');

require('aui.radiogroup');

require('aui.debug');

require('aui.select');

require('jquery.toaster');

require('./js/component');

window.AUI.Loader.loadScripts(
    [
        '//cdn.bootcss.com/marked/0.3.6/marked.min.js'
    ]
).then(function () {
    require("aui.markdown");
});

let TokenManager = require("../framework/js/tokenManager");
let Validator = require("../framework/js/aui/validate");
let Cookies = require("../framework/js/cookie");
let RequestService = require("../framework/js/services/request.service");
let Lscache = require("../framework/js/lscache");
let { PageComonComponent } = require("./js/main");

window.globalComponents = {};
window.globalComponents.PageComonComponent = PageComonComponent;
window.globalPages = {};

function guid() {
    function s4() {
        return Math.floor((1 + Math.random()) * 0x10000)
            .toString(16)
            .substring(1);
    }
    return Date.now() + "__" + s4() + s4() + '-' + s4() + '-' + s4() + '-' +
        s4() + '-' + s4() + s4() + s4();
}

var rootcontroller = {
    headerPage: '<p>this is headerPage</p>',//头部页面
    footerPage: '苏州开心盒子软件有限公司<br>&copy; 2017',//尾部页面
    currPath: '',//当前路径k
    currPage: ''//当前页面,
};
rootcontroller.app = {
    name: '苏州开心盒子',
    version: '1.3.3',
    // for chart colors
    color: {
        primary: '#7266ba',
        info:    '#23b7e5',
        success: '#27c24c',
        warning: '#fad733',
        danger:  '#f05050',
        light:   '#e8eff0',
        dark:    '#3a3f51',
        black:   '#1c2b36'
    },
    settings: {
        themeID: 1,
        navbarHeaderColor: 'bg-info dker',
        navbarCollapseColor: 'bg-info dker',
        asideColor: 'bg-light dker b-r',
        headerFixed: true,
        asideFixed: false,
        asideFolded: false,
        asideDock: false,
        container: false
    },
    tpl: {
        path: "tpl/"
    },
    applicationGUID: guid(),
    navs: [],
    globalUserName: ""
};

rootcontroller.app.hideFooter = true;
rootcontroller.services = {};
rootcontroller.Cookies = Cookies;
rootcontroller.constatnts = {};
rootcontroller.constatnts.LASTROUTE = "lastroute";
rootcontroller.constatnts.USERINFO = "userinfo";
rootcontroller.constatnts.DEFAULTPAGE = "/";

Vue.use(VueRouter);

// 1. 定义（路由）组件。
let adminroutes = require("./js/route");

let globalroutenavs = [
    { path: '/', redirect: '/admin/index/' },
    {
        path: "/admin",
        component: require("./js/admin.js"),
        children: adminroutes
    },
    {
        path: "/404",
        component: require("./js/404.js")
    },
    {
        name: "登录",
        path: "/signin",
        component: require("./js/signin.js")
    }
];

// 2. 定义路由
const routes = globalroutenavs;

// 3. 创建 router 实例，然后传 `routes` 配置
const router = new VueRouter({
    routes // （缩写）相当于 routes: routes
});

router.beforeEach((to, from, next) => {
    var userInfo = Lscache.get(rootcontroller.constatnts.USERINFO);
    if (to.matched.length > 0) {
        if (to.meta.interceptor) {
            if (!to.meta.interceptor(to, from, userInfo)) {
                next({
                    path: "/404"
                });
            }
        } 
        if (to.path != "/signin") {
            Lscache.set(rootcontroller.constatnts.LASTROUTE, {
                name: to.name,
                fullPath: to.fullPath,
                hash: to.hash,
                path: to.path,
                query: to.query,
                params: to.params,
                meta: to.meta
            });
        }
        next();
    } else {
        next({
            path: "/404"
        });
    }
});

validate.validators.pattern = function(value, options, key, attributes) {
    var isready = options.regex.test(value);
    if (!isready) {
        return options.message || "is totally wrong";
    }
};

window.$ = $;
window._ = _;
window.Vue = Vue;
window.Validator = Validator;
window.Lscache = Lscache;

Vue.use(VueI18n);
var langs = require("./js/lang");
var i18n = new VueI18n({
    locale: 'zh-CN', // set locale
    messages: langs, // set locale messages
});

window.createApp = function () {
    rootcontroller.tokenManager = new TokenManager(
        window.globalConfig.constants.API_COOKIE_TOKEN_NAME,
        window.globalConfig.constants.API_COOKIE_LIFE_TIME,
        window.globalConfig.constants.API_COOKIE_LIFE_TIME - window.globalConfig.constants.API_COOKIE_UPDATE_TIME,
        window.globalConfig.constants.API_COOKIE_DOMAIN
    );

    function _handleCrosLiteRequest(type, err, resp, resolve, reject) {
        if (err) {
            reject({
                response: {
                    data: err
                }
            });
        }
        
        var res = {};
        try {
            if (!resp || !resp.responseText) {
                reject({
                    response: {
                        data: {
                            code: 2002,
                            message: ""
                        }
                    }
                });
                return false;
            }
            res = JSON.parse(resp.responseText);
            if (res.code && res.status > 399 && res.message) {
                reject({
                    response: {
                        data: res
                    }
                });
            } else {
                resolve({
                    data: res
                })
            }
        } catch(e) {
            console.log(e);
        }
        return res;
    }

    rootcontroller.testrefresh = function () {
        rootcontroller.services.requestService._post("tokens", {
            account: "bg",
            password: "qq111111"
        }, {});
    };

    rootcontroller.Corslite = function(url, callback, cors, type = "GET") {
        var sent = false;

        if (typeof window.XMLHttpRequest === 'undefined') {
            return callback(Error('Browser not supported'));
        }

        if (typeof cors === 'undefined') {
            var m = url.match(/^\s*https?:\/\/[^\/]*/);
            cors = m && (m[0] !== location.protocol + '//' + location.hostname +
                (location.port ? ':' + location.port : ''));
        }

        var x = new window.XMLHttpRequest();

        function isSuccessful(status) {
            return status >= 200 && status < 300 || status === 304;
        }

        if (cors && !('withCredentials' in x)) {
            // IE8-9
            x = new window.XDomainRequest();

            // Ensure callback is never called synchronously, i.e., before
            // x.send() returns (this has been observed in the wild).
            // See https://github.com/mapbox/mapbox.js/issues/472
            var original = callback;
            callback = function() {
                if (sent) {
                    original.apply(this, arguments);
                } else {
                    var that = this, args = arguments;
                    setTimeout(function() {
                        original.apply(that, args);
                    }, 0);
                }
            }
        }

        function loaded() {
            if (
                // XDomainRequest
            x.status === undefined ||
            // modern browsers
            isSuccessful(x.status)) callback.call(x, null, x);
            else callback.call(x, x, null);
        }

        // Both `onreadystatechange` and `onload` can fire. `onreadystatechange`
        // has [been supported for longer](http://stackoverflow.com/a/9181508/229001).
        if ('onload' in x) {
            x.onload = loaded;
        } else {
            x.onreadystatechange = function readystate() {
                if (x.readyState === 4) {
                    loaded();
                }
            };
        }

        // Call the callback with the XMLHttpRequest object as an error and prevent
        // it from ever being called again by reassigning it to `noop`
        x.onerror = function error(evt) {
            // XDomainRequest provides no evt parameter
            callback.call(this, evt || true, null);
            callback = function() { };
        };

        // IE9 must have onprogress be set to a unique function.
        x.onprogress = function() { };

        x.ontimeout = function(evt) {
            callback.call(this, evt, null);
            callback = function() { };
        };

        x.onabort = function(evt) {
            callback.call(this, evt, null);
            callback = function() { };
        };

        // GET is the only supported HTTP Verb by XDomainRequest and is the
        // only one supported here.
        x.open("get", url, true);

        // Send the request. Sending data is not supported.
        x.send(null);
        sent = true;

        return x;
    };
    rootcontroller.adminroutes = adminroutes;
    rootcontroller.currentPagecontext = {};
    rootcontroller.systemlinks = [];
    rootcontroller.services.requestService =  new RequestService(
        window.globalConfig.constants.API_HOST, "", window.globalConfig.constants.API_VERSION, rootcontroller.app.applicationGUID, axios);
    function _searchPage(context) {
        var res = {};
        if (!context.$parent.attachChildComponentReady){
            res = _searchPage(context.$parent);
        } else {
            res = context.$parent;
        }
        return res;
    }

    rootcontroller.services.requestService.setJSONPall = function (params, expand, requesturl) {
        var self = this;
        var expandStr = expand + '';
        var url = self.buildUrl(params, expandStr, requesturl);
        params.proxy_api=window.globalConfig.constants.API_HOST;
        params.old = true;
        params.m = window.globalConfig.constants.API_VERSION + "/" + expand;
        params.__method = "GET";

        return new Promise(function (resolve, reject) {
            rootcontroller.Corslite(url, function(err, resp) {
                return _handleCrosLiteRequest("GET", err, resp, resolve, reject);
            }, true);
        });
    };

    rootcontroller.services.requestService.setJSONPget = function (id, params, expand) {
        var self = this;
        var expandStr = expand + "/" + id;
        var url = self.buildUrl(params, expandStr);
        params.proxy_api=window.globalConfig.constants.API_HOST;
        params.old = true;
        params.m = window.globalConfig.constants.API_VERSION + "/" + expand + "/" + id;
        params.__method = "GET";
        
        return new Promise(function (resolve, reject) {
            rootcontroller.Corslite(url, function(err, resp) {
                return _handleCrosLiteRequest("GET", err, resp, resolve, reject);
            }, true);
        });
    };

    rootcontroller.services.requestService.setJSONPpost = function (data, params, expand, url) {
        var self = this;
        var expandStr = '';
        params.proxy_api=window.globalConfig.constants.API_HOST;
        params.data = JSON.stringify(data);
        params.old = true;
        params.m = window.globalConfig.constants.API_VERSION + "/" + expand;
        params.__method = "POST";
        var url = self.buildUrl(params, expandStr,  window.globalConfig.constants.API_HOST + "/proxy", "&callback=s?");
        return new Promise(function (resolve, reject) {;
            rootcontroller.Corslite(url, function(err, resp) {
                return _handleCrosLiteRequest("POST", err, resp, resolve, reject);
            }, true);
        });
    };

    rootcontroller.services.requestService.setJSONPput = function (id, data, params, expand, url) {
        var self = this;
        var expandStr = "";
        params.proxy_api=window.globalConfig.constants.API_HOST;
        params.data = JSON.stringify(data);
        params.old = true;
        params.m = window.globalConfig.constants.API_VERSION + "/" + expand + "/" + id;
        params.__method = "PUT";

        var url = self.buildUrl(params, expandStr,  window.globalConfig.constants.API_HOST + "/proxy", "&callback=s?");
        return new Promise(function (resolve, reject) {
            rootcontroller.Corslite(url, function(err, resp) {
                return _handleCrosLiteRequest("PUT", err, resp, resolve, reject);
            }, true);
        });
    };

    rootcontroller.setOldAppCookie = function (response, tokenManager, name) {
        var expire = tokenManager._createExpireFromDate(new Date(), tokenManager.totalTime);
        Cookies.set("console.aunbox.cn.dev", response.data.token, {
            expires: expire,
            domain: tokenManager.domain
        });
        Cookies.set("console.aunbox.cn.dev__expires", expire.valueOf(), {
            expires: expire,
            domain: tokenManager.domain
        });
        Cookies.set("console.aunbox.cn.dev__name", name, {
            expires: expire,
            domain: tokenManager.domain
        });
    };

    rootcontroller.getUserInfo = function (token) {
        return rootcontroller.services.requestService._all("user-infos", {
            token: token
        });
    };

    rootcontroller.langs = langs;

    rootcontroller.getPage = function (context) {
        return _searchPage(context);
    };

    rootcontroller.globaldata = {};

    rootcontroller.globaldata.gloablDatatableDefine = {
        "remark": {
            key: function (item) {
                return "备注";
            },
            value: function (item) {
                return {
                    componentname: "aui-truncate-text",
                    value: item.remark,
                    len: 30
                };
            }
        }
    };

    rootcontroller.getUploadUrl = function () {
        var url = window.globalConfig.constants.API_HOST + '/'
            + 'upload.php?token='
            + rootcontroller.tokenManager.getToken()
        return url;
    };

    rootcontroller.saveGetUserInfo = function () {
        var userInfo = {};
        if (Lscache.get(rootcontroller.constatnts.USERINFO)) {
            userInfo = Lscache.get(rootcontroller.constatnts.USERINFO);
        }
        return userInfo;
    };

    // 路由
    rootcontroller.globalroutenavs = adminroutes.filter(function (v) {
        return v.hasOwnProperty("icon");
    });
    // 二级子路由
    rootcontroller.subroutenavs = [];
    _.forEach(rootcontroller.services, function (service) {
        service.onError = function (e) {
            // console.dir(e);
            if (service._onError) {
                service._onError(e);
            }
            if (!e.response) {
                e = {
                    response: {
                        data: {
                            message: "not found"
                        }
                    }
                }
            }
            if (rootcontroller.anuAdmin) {
                rootcontroller.anuAdmin.handleGlobalError(e);
            } else {
                window.aui.toast({
                    heading: '消息提示',
                    text: e.response.data.message,
                    icon: "error"
                });
            }
            if (rootcontroller.currentPagecontext.onError) {
                rootcontroller.currentPagecontext.onError(e);
            }
        };
    });
    window.rootcontroller = rootcontroller;

    new Vue({
        el: "#app",
        data: rootcontroller,
        i18n: i18n,
        router
    });
};

window.loadIndexReady();